<?php
    namespace Home\Controller;

    use \Think\Controller;

    class SearchController extends HomeController
    {
        // 搜索主页
        public function index()
        {
            // 判断搜索条件
            if (empty($_GET['name'])) {
                $this->error('没有搜索条件...');
                exit;
            }

            //判断分页条件
            if(!empty($_GET['p']) && intval($_GET['p']) > 0) {
                $p = intval($_GET['p']);
            } else {
                $p = 1;
            }

            // 判断查询模式的条件
            if(!empty($_GET['type'])) {
                $type = $_GET['type'];
                if ( !in_array($type, array('question','article','user','topic'))){
                    $type = 'question';
                }
            } else {
                $type = 'question';
            }

            // var_dump($type);
            unset($_GET['type']);
            unset($_GET['p']);

            $name = $_GET['name'];
            // 搜索栏的滚动事件
            if ($name == '') {
                $data = null;
            } else {
                switch ($type) {
                    case 'question':
                        $q = M('question');
                        // 2 问题
                        $where = "display=1 AND name LIKE '%{$name}%'";
                        $data = $q->field('id, name, user_id, user_name')->where($where)->order('datetime')->page($p, 10)->select(); //2 是问题
                        break;
                    case 'user':
                        $u = M('user');
                        // 搜索三个表格
                        $where = "name LIKE '%{$name}%'"; // 0是用户
                        $data = $u->field('id, name, image')->where($where)->page($p, 10)->select();
                        break;
                    case 'article':
                        // 1 文章
                        $a = M('article');
                        $where = "display=1 AND title LIKE '%{$name}%'";
                        $data = $a->field('id, title')->where($where)->order('datetime')->page($p, 10)->select();
                        break;
                    case 'topic':
                        $t = M('topics');
                        // 3是话题
                        $where = "name LIKE '%{$name}%'";
                        $data = $t->field('id, name, image')->where($where)->order('id')->page($p, 10)->select(); //3 是问题
                        break;
                }
            }
            // 查询完释放类型
            
            // var_dump($data);
            $this->assign('p', $p+1);
            $this->assign('name', $name);
            $this->assign('type', $type);
            $this->assign('data', $data);
            $this->assign('title', '搜索 - 知乎');
            $this->display('Search/index');
        }






    }